package com.qn.example.filters;

import com.alibaba.fastjson.JSON;
import com.qn.example.pojo.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author 21276
 * @version 1.0
 * @date 2023/5/3 14:39
 *
 * 过滤器: 解决退出登录，重新刷新页面，返回到登录页面。
 */
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //创建专门用来比较请求的对象
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将请求对象和响应对象转成HTTP的请求和响应
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求中的所有的uri
        String requestURI = request.getRequestURI();
        //定义一个要放行的路径的数组
        String[] uris = {"/backend/**","/front/**","/employee/login","/employee/logout","/common/**","/user/sendMsg","/user/login"};
        //比较当前的请求是否是预定要放行的请求，如果是则直接放行，如果不是则验证是否已经登录，如果登录则放行
        boolean flag = checkUrl(uris,requestURI);
        //如果是当前请求的路径是预定的路径中的一个则直接放行
        if(flag){
            //放行
            filterChain.doFilter(request,response);
            //结束
            return;
        }
        //验证是否已经登录
        HttpSession session = request.getSession();
        if (session.getAttribute("user")!=null){
            //登录直接放行
            //放行
            filterChain.doFilter(request,response);
            //结束
            return;
        }

        //如果没有登录需要自己手动返回没有登录的json标识:NOTLOGIN
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean checkUrl(String[] uris, String requestURI) {
        for (String uri : uris) {
            if (antPathMatcher.match(uri,requestURI)){
                return true;
            }
        }
        return false;
    }
}
